<div class="col-sm-3 pad0 zskZtree" style="position: relative">
    <div class="zTree">
        <div class="zTreeDemoBackground left" style="height: 100%">
            <ul id="treeDemo" class="ztree" style="padding: 0"></ul>
        </div>
    </div>
</div>

<script type="text/javascript">
    require(['jquery'], function () {
        var winHeight=$(window).height();
        $('.zskZtree .zTree').css('height',winHeight-238+'px');
    });
    //
    function getSetting(zTree) {
        var setting = {
            check: {enable: false},
            data: {
                key: {title: "name"},
                simpleData: {enable: true,idKey: "id", pId: "pId"}
            },
            async: {
                enable : false,
                url : "",
                autoParam : ['cat_id', 'cat_name'],
                contentType : "application/json",
                dataType: "json",
                type : 'post'
            },
            edit: {
                enable: true,
                drag : {
                    isCopy: false,
                    isMove : false,
                    inner: false,//拖拽到目标节点时，设置是否允许成为目标节点的子节点
                },
                removeTitle: "删除",
                renameTitle: "修改",
                showRemoveBtn: function (treeId, treeNode) {
                    return treeNode.id == 0 ? false : true;
                },
                showRenameBtn: function (treeId, treeNode) {
                    return treeNode.id == 0 ? false : true;
                }
            },
            view: {
                removeHoverDom: function (treeId, treeNode) {
                    $("#"+treeNode.tId+'_addBtn').unbind().remove();
                    $("#"+treeNode.tId+'_moveupBtn').unbind().remove();
                    $("#"+treeNode.tId+'_movedownBtn').unbind().remove();
                },
                addHoverDom: function (treeId, treeNode) {
                    var sObj = $("#" + treeNode.tId + "_span");

                    //添加节点
                    if (treeNode.editNameFlag || $("#"+treeNode.tId+'_addBtn').length>0) return;
                    if (treeNode.isParentNode == true || treeNode.id == 0) {
                        var title = treeNode.id == 0 ? '添加一级分类' : '添加二级分类';
                        var addStr = "<span class='button add' id='" + treeNode.tId + "_addBtn' title='" + title + "' onfocus='this.blur();' ></span>";
                        sObj.after(addStr);
                    }
                    var btn = $("#"+treeNode.tId + '_addBtn');
                    if (btn) btn.bind("click", function(){
                        if (treeNode.isParentNode == true) {
                            var cat_msg = treeNode.id == 0 ? '请输入一级分类名' : '请输入二级分类名';
                            cat_msg += '(最多8个字)';
                            layer.prompt({title: cat_msg, formType: 0, value: '', maxlength: 8, success: function (layero, index) {
                                $(".layui-layer-input").on('keydown',function(e){
                                    if(e.keyCode === 13){
                                        var cat_name = $(this).val();
                                        var data = {
                                            'cat_id' : treeNode.id,
                                            'cat_name' : cat_name
                                        };
                                        addCate(data);
                                    }
                                });
                            }}, function(value, index, elem){
                                var data = {
                                    'cat_id' : treeNode.id,
                                    'cat_name' : value
                                };
                                addCate(data);
                            });
                        } else {
                            return false;
                        }
                    });

                    //向下移动节点
                    if ($("#"+treeNode.tId+'_movedownBtn').length > 0) return;
                    if (treeNode.id != 0) {
                        var addMoveDownStr = '';
                        if ((treeNode.isParentNode === true && treeNode.count_parent_list > 1) || (treeNode.isParentNode === false && treeNode.count_child_list > 1)) {
                            addMoveDownStr = "<span class='movedown' id='" + treeNode.tId + "_movedownBtn' title='下移分类' onfocus='this.blur();'><img src='"+"{KB_WEB_BACK_IMG}/move_down.png"+"' alt='' style='height: 17px; border: 1px solid #999;margin-bottom: 2px;'></span>";
                        }
                        sObj.after(addMoveDownStr);
                    }
                    var btn_move_down = $("#"+treeNode.tId + '_movedownBtn');
                    if (btn_move_down) btn_move_down.bind("click", function(){
                        var data = {
                            cat_id : treeNode.id,
                            sort_order : treeNode.sort_order,
                            type: 'down'
                        };
                        $.post("{php echo $this->createWebUrl('knowledge', array('act' => 'sortCate'))}", data, function (data) {
                            if(data.code === 200){
                                layer.msg(data.msg, {icon: 1,time:1000});
                                initzTreeData(zTree, setting);
                            } else {
                                layer.msg(data.msg, {icon: 0,time:1000});
                                return false;
                            }
                        });
                    });

                    //向上移动节点
                    if ($("#"+treeNode.tId+'_moveupBtn').length > 0) return;
                    if (treeNode.id != 0) {
                        var addMoveUpStr = '';
                        if ((treeNode.isParentNode === true && treeNode.count_parent_list > 1) || (treeNode.isParentNode === false && treeNode.count_child_list > 1)) {
                            addMoveUpStr = "<span class='moveup' id='" + treeNode.tId + "_moveupBtn' title='上移分类' onfocus='this.blur();' ><img src='"+"{KB_WEB_BACK_IMG}/move_up.png"+"' alt='' style='height: 17px; border: 1px solid #999;margin-bottom: 2px;hover: color'></span>";
                        }
                        sObj.after(addMoveUpStr);
                    }
                    var btn_move_up = $("#"+treeNode.tId + '_moveupBtn');
                    if (btn_move_up) btn_move_up.bind("click", function(){
                        var data = {
                            cat_id : treeNode.id,
                            sort_order : treeNode.sort_order,
                            type: 'up'
                        };
                        $.post("{php echo $this->createWebUrl('knowledge', array('act' => 'sortCate'))}", data, function (data) {
                            if(data.code === 200){
                                layer.msg(data.msg, {icon: 1,time:1000});
                                initzTreeData(zTree, setting);
                            } else {
                                layer.msg(data.msg, {icon: 0,time:1000});
                                return false;
                            }
                        });
                    });

                }
            },
            callback: {
                onDblClick: function (event, treeId, treeNode, clickFlag) {
                    if (treeNode.isParentNode == true) {
                        window.location.href = "{php echo $this->createWebUrl($_GPC['do'], array('act' => $_GPC['act']));}&cat_id=" + treeNode.id;
                    } else {
                        return false;
                    }
                },
                onRename: function (event, treeId, treeNode) {
                    var data = {cat_id: treeNode.id, cat_name: treeNode.name};
                    $.post("{php echo $this->createWebUrl('knowledge', array('act' => 'editCate'))}", data, function (data) {
                        if(data.code === 200){
                            layer.msg(data.msg, {icon: 1,time:1000});
                        } else {
                            layer.msg(data.msg, {icon: 0,time:1000});
                            initzTreeData(zTree, setting);
                        }
                    });
                },
                beforeRemove: function (treeId, treeNode) {
                    return confirm('删除后无法恢复，是否确定删除？');
                    /*var flag_ = null;
                    layer.confirm('删除后无法恢复，是否确定删除？', {
                        btn: ['确定', '取消'] //可以无限个按钮
                    }, function(index, layero){
                        flag_ = true;
                    }, function(index){
                        layer.close(index);
                        flag_ = false;
                    });
                    return flag_;*/
                },
                onRemove: function (event, treeId, treeNode) {
                    var data = {cat_id: treeNode.id};
                    $.post("{php echo $this->createWebUrl('knowledge', array('act' => 'delCate'))}", data, function (data) {
                        if(data.code === 200){
                            layer.msg(data.msg, {icon: 1,time:1000});
                        } else {
                            layer.msg(data.msg, {icon: 0,time:1000});
                            initzTreeData(zTree, setting);
                        }
                    });
                }
            }
        };
        return setting;
    }

    //初始化树数据
    function initzTreeData(zTree, setting) {
        var cat_id = getQueryString('cat_id');
        var all_checked_status = cat_id == null || cat_id == 0 ? true : false;
        $.post("{php echo $this->createWebUrl('knowledge', array('act' => 'getCateList'));}", {}, function (data) {
            var zNodes = [{id: 0, pId: 0, name: '全部分类', isParentNode: true, open: true, checked: true}];
            if (data.code === 200) {
                $.each(data.category_list, function (index, element) {
                    var checked_status = all_checked_status == true ? true : (cat_id == element.cat_id ? true : false);
                    var tmpNodes = {id: element.cat_id, pId: 0, name: element.cat_name, sort_order: element.sort_order, isParentNode: true, open: true, checked: checked_status, count_parent_list: element.count_parent_list};
                    zNodes.push(tmpNodes);
                    if (element.child_list.length > 0) {
                        $.each(element.child_list, function (i, v) {
                            var tmpNodes_tmp = {id: v.cat_id, pId: element.cat_id, name: v.cat_name, sort_order: v.sort_order, isParentNode: false,checked: checked_status,count_child_list: element.count_child_list};
                            zNodes.push(tmpNodes_tmp);
                        });
                    }
                });
            }
            zTree.init($("#treeDemo"), setting, zNodes);
        });
    }

    //添加分类
    function addCate(data) {
        $.post("{php echo $this->createWebUrl('knowledge', array('act' => 'addCate'))}", data, function (data) {
            if(data.code === 200){
                layer.msg(data.msg, {icon: 1,time:1000});
                setTimeout(function () {
                    window.location.reload();
                }, 1000)
            } else {
                layer.msg(data.msg, {icon: 0,time:1000});
                return false;
            }
        });
    }

    //获取当前url参数
    function getQueryString(name) {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return unescape(r[2]); return null;
    }

    //js截取字符显示
    function subString (str,n){
        n = n||20;
        var r=/[^\x00-\xff]/g;
        if(str.replace(r,"mm").length<=n){return str;}
        var m=Math.floor(n/2);
        for(var i=m;i<str.length;i++){
            if(str.substr(0,i).replace(r,"mm").length>=n){
                return str.substr(0,i)+"...";
            }
        }
        return str;
    }

</script>